package com.glkj.vipsystem.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.glkj.vipsystem.common.utils.Constant;
import com.glkj.vipsystem.core.sms.ISmsSendEvent;
import com.glkj.vipsystem.core.sms.SmsPluginFactory;
import com.glkj.vipsystem.core.sms.aliyun.AliyunSmsTemplate;
import com.glkj.vipsystem.entity.ao.SmsCodeAO;
import com.glkj.vipsystem.mapper.SmsCodeMapper;
import com.glkj.vipsystem.service.ISmsCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * SmsCode 服务实现类
 * </p>
 *
 * @author Limuchan
 * @since 2019-09-24 10:58:47
 */
@Service
public class SmsCodeService extends ServiceImpl<SmsCodeMapper, SmsCodeAO> implements ISmsCodeService {
    /**
     * 验证码效验
     *
     * @param type   验证码类型
     * @param mobile 手机号
     * @param code   验证码
     * @return true：成功  false：失败
     */
    @Override
    public boolean validate(Constant.SmsCodeType type, String mobile, String code) {
        SmsCodeAO smsCode = selectById(type.key().concat(mobile));
        if (smsCode == null) {
            return false;
        }
        boolean flag = smsCode.getCode().equals(code) && smsCode.getExpireTime().getTime() >= System.currentTimeMillis();
        if (flag) {
            deleteById(smsCode.getCodeKey());
        }
        return flag;
    }

    /**
     * 发送验证码
     *
     * @param template 短信模板
     * @param type    验证码类型
     * @param mobile  手机号
     * @param seconds 有效时间(s)
     */
    @Override
    public void send(AliyunSmsTemplate template,Constant.SmsCodeType type, String mobile, int seconds) {
        if (type == null || StringUtils.isBlank(mobile)) {
            return;
        }
        // 发送验证码
        String key = type.key().concat(mobile);
        SmsCodeAO smsCode = selectById(key);
        String code = RandomUtil.randomNumbers(6);
        Date expireDate = DateUtil.offset(new Date(), DateField.SECOND, seconds);
        if (smsCode != null) {
            smsCode.setCode(code);
            smsCode.setExpireTime(expireDate);
            super.updateById(smsCode);
        } else {
            smsCode = new SmsCodeAO();
            smsCode.setCodeKey(key);
            smsCode.setCode(code);
            smsCode.setExpireTime(expireDate);
            super.insert(smsCode);
        }
        // 发送验证码
        Map<String, Object> param = new HashMap<>();
        // 模板code
        param.put("template_code", template.getCode());
        param.put("code", code);
        ISmsSendEvent smsPlugin = SmsPluginFactory.getSmsPlugin();
        smsPlugin.onSend(mobile, "", param);
    }
}
